package com.sanbi.shield.client.core.idempotent;

import com.sanbi.shield.client.core.exceptions.IdempotentCacheException;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Client幂等处理器缓存
 *
 * @author XiaoQingqing
 * @since 2024/08/22
 */
public class ClientIdempotentHandlerCache {
    /**
     * 对象容器
     */
    private static final Map<String, Object> OBJECT_CONTAINER = new ConcurrentHashMap<>();
    /**
     * 方法容器
     */
    private static final Map<String, Method> METHOD_CONTAINER = new ConcurrentHashMap<>();

    /**
     * 添加缓存
     *
     * @param key    标识
     * @param object 对象
     * @param method 方法
     */
    public static void push(String key, Object object, Method method){
        if(METHOD_CONTAINER.containsKey(key)){
            throw new IdempotentCacheException("幂等方法标识[key="+ key +"]定义重复");
        }
        Object oldObject = OBJECT_CONTAINER.put(key, object);
        if(null != oldObject && !Objects.equals(oldObject, object)){
            throw new IdempotentCacheException("幂等方法标识[key="+ key +"]定义所在类重复");
        }
        METHOD_CONTAINER.put(key, method);
    }

    /**
     * 获取缓存对象
     *
     * @param key 标识
     * @return 对象
     */
    public static Object getObject(String key){
        return OBJECT_CONTAINER.get(key);
    }

    /**
     * 获取缓存方法
     *
     * @param key 标识
     * @return 方法
     */
    public static Method getMethod(String key){
        return METHOD_CONTAINER.get(key);
    }
}
